from flask import Blueprint, request, current_app
from flask_json import as_json
from flask_jwt_extended import jwt_required

from .is_staff_user import is_staff_user
from app import db
from app.models import CommonResult, CommonPage, Tag
from app.auth.auth_decorator import has_role
from app.common.enums import RoleCodeEnum

log = current_app.logger
admin_tag = Blueprint('admin_tag', __name__, url_prefix='/admin/tag')


# 注册蓝图
def register_controller(app):
    app.register_blueprint(admin_tag)


# 分页查询
@admin_tag.post('/page')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def page():
    data = request.get_json()
    current = 1
    page_size = 10
    query = Tag.query
    if data:
        current = data.get('current') or 1
        page_size = data.get('page_size') or 10
        name = data.get('name')
        if name and name.strip():
            query = query.filter(Tag.name.like('%{keyword}%'.format(keyword=name)))
    # 分页查询
    page_data = query.paginate(
        page=current,
        per_page=page_size,
        error_out=False
    )
    return CommonResult(data=CommonPage(page_data))


# 添加记录
@admin_tag.post('/add')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def add():
    data = request.get_json()
    if data and data.get('name') is None:
        return CommonResult(code=500, msg='请输入标签名称')
    # 查询标签是否已经存在
    tag = Tag.query.filter_by(name=data.get('name')).first()
    if tag:
        return CommonResult(code=500, msg='标签已存在')
    # 填充数据
    record = Tag()
    record.__dict__.update(data)
    # 保存数据库
    db.session.add(record)
    db.session.commit()
    return CommonResult(data=data, msg='保存成功')


# 获取详情
@admin_tag.get('/get/<int:tag_id>')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def info(tag_id):
    tag = Tag.query.get(tag_id)
    return CommonResult(data=tag, msg='获取成功')


# 修改信息
@admin_tag.post('/update')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def update():
    data = request.get_json()
    # 更新用户信息
    tag_id = int(data.get('id'))
    tag = Tag.query.get(tag_id)
    if tag:
        # 根据名称查询记录是否已经存在
        exist_tag = Tag.query.filter_by(name=data.get('name')).first()
        if exist_tag and not exist_tag.id == tag_id:
            return CommonResult(code=500, msg='标签已存在')
        tag.name = data.get('name')
        db.session.commit()
        return CommonResult(data=data, msg='修改成功')
    return CommonResult(code=500, msg='修改的记录不存在')


# 删除记录
@admin_tag.get('/delete/<int:tag_id>')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def delete(tag_id):
    # 判断分类是否存在
    record = Tag.query.get(tag_id)
    if record is None:
        return CommonResult(code=500, msg='删除的记录不存在')
    # 删除记录
    db.session.delete(record)
    db.session.commit()
    return CommonResult(msg='删除成功')
